import axios from 'axios'
import { ipcMain } from 'electron-better-ipc'
import { Jimp } from 'jimp'
import fs from 'node:fs'
import path from 'node:path'

export interface IDownloadImgParams {
    // 图片地址
    url: string
    // 图片尺寸
    targetSize: {
        width: number
        height: number
    }
    // 目标路径，可以是文件或者文件夹，如果是文件则会直接替换
    targetPath: string
    // 原文件名
    originalFileName: string
}

export const downloadImg = async (params: IDownloadImgParams) => {
    console.log('downloadImg', params)
    // 下载图片
    const response = await axios.get(params.url, {
        responseType: 'arraybuffer'
    })

    // 目标路径，如果是文件夹则拼接个文件名
    let finalTargetPath = params.targetPath as `${string}.${string}`
    const stats = fs.statSync(finalTargetPath)
    if (stats.isDirectory()) {
        finalTargetPath = path.join(finalTargetPath, params.originalFileName + '.png') as `${string}.${string}`
    }

    // 更改尺寸并写入
    const { width, height } = params.targetSize
    const readed = await Jimp.read(response.data)
    const resized = await readed.resize({
        w: width,
        h: height
    })
    await resized.write(finalTargetPath)
    return 'success'
}

ipcMain.answerRenderer('downloadImg', downloadImg)
